/*
 * @AD 
 * @創建時間：T20201028
 * @作者：Viking
 * @版本號：V2.0
 * @注：
 */
#include "AD.h"

void fun_ADC_Init()
{
	//SET_PB2_AN2();
}
/**
 * @brief 开启ADC通道，并获取ADC值
 *
 * @param channel ADC采样通道
 * @return unsigned int
 */
unsigned int fun_Get_ADC(unsigned char channel)
{
	unsigned char i;
	unsigned int adcdata;
	SET_ADC_DATA_0_11();
	_adpgaen = 1;
	_vbgen = 1;
	_savrs3 = 1; _savrs2 = 0; _savrs1 = 1; _savrs0 = 0; //VREF = VBG * 2 =2.04V = 2040mV
	SET_ADC_POWER_ON();
	//SET_PA6_VREF_VDD();
	SET_ADC_CLOCK_SYS_1(); //1MHz
	GCC_DELAY(2000);	
//	V_SysClock_1MHz_Init();
//	GCC_DELAY(10000);    //4us *10000 = 40ms

	switch (channel)
	{
		case ADC_CHANNEL_AN0:	SET_ADC_CHANNEL_AN0(); SET_PB0_AN0();	break;
		case ADC_CHANNEL_AN1:	SET_ADC_CHANNEL_AN1(); SET_PB1_AN1();	break;
		case ADC_CHANNEL_AN2:	SET_ADC_CHANNEL_AN2(); SET_PB2_AN2();	break;
		case ADC_CHANNEL_AN3:	SET_ADC_CHANNEL_AN3(); SET_PA4_AN3();	break;
		case ADC_CHANNEL_AN4:	SET_ADC_CHANNEL_AN4(); SET_PA5_AN4();	break;
		case ADC_CHANNEL_AN5:	SET_ADC_CHANNEL_AN5(); SET_PA6_AN5();	break;
		case ADC_CHANNEL_AN6:	SET_ADC_CHANNEL_AN6(); SET_PA7_AN6();	break;
		case ADC_CHANNEL_AN7:	SET_ADC_CHANNEL_AN7(); SET_PB3_AN7();	break;
		
		case ADC_CHANNEL_VDD_4 :SET_ADC_CHANNEL_VDD_4();	break; 
		default:	break;
	}
	for(i=0;i<1;i++)
	{
		SET_ADC_STARTCONVERT();
		while (_adbz);
		adcdata = 0;
		adcdata = _sadol;
		adcdata += _sadoh*256;
	}
	
	
	SET_ADC_POWER_OFF();
//	V_SysClock_32kHz_Init();
	//CLR_PA6_VREF_VDD();
	_adpgaen = 0;
	_vbgen = 0;
	return adcdata;
}

unsigned char fun_Get_BATValue()
{
	unsigned int adcdata;
	unsigned int BatValue;
	adcdata = fun_Get_ADC(ADC_CHANNEL_VDD_4); //4.2V
	//gu16v_BatValue = (2040 * adcdata) / 4096 * 4;
	
	BatValue = 2 * (adcdata-450);//誤差補償
	//3000 - 4200
	if(BatValue >= 3000)
	{
		BatValue = (BatValue - 3000) / 12; //%
	}
	else
	{
		BatValue = 0; //0%
	}
	if(BatValue > 100)
	{
		BatValue = 100;
	}
	return BatValue;
}